// index.js
// 获取应用实例
import { activityApi } from '/api/activity'
import { knowAboutApi } from '/api/knowAbout'
import { knowledgeApi } from '/api/konwledge'
import { userApi } from '/api/user'
import { getUser } from '/store/actions'
import { isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event, $utils } from '/utils'

Page({
  data: {
    navigationHeight: 0,
    access: GlobalData.access,
    noMore: false,
    navData: [
      { id: 2, name: '主播', offset: 0, isLastPage: false, show: false },
      { id: 6, name: '球员', offset: 0, isLastPage: false, show: false },
    ] as any[],
    currentTab: 0,
    navScrollLeft: 0,
    list: [] as any[],
    currentTabList: [] as number[],
    followingOperations: [] as number[],
    searchText: '',
    keyword: '',
    limit: 20,
    user: {} as DomoUser,
    show: false,
    paytoast: false,
    chooseTopic: {} as DomoTopic,
    focus: true,
    currencyName: GlobalData.currencyName,
  },

  async onLoad({ index = 0 }) {
    const windowWidth = GlobalData.clientWidth
    //每个tab选项宽度占1/5
    const singleNavWidth = windowWidth / 6
    this.setData({
      currentTab: +index,
      navScrollLeft: (+index - 2) * singleNavWidth,
      currencyName: GlobalData.currencyName,
    })
    $event.on('erorr:integral', this, ({ paytoast, topic }) => {
      this.setData({
        paytoast,
        chooseTopic: topic,
      })
    })
    if (isLogin()) {
      const user = getUser()
      this.setData({
        user,
      })
    }
  },

  onShareAppMessage() {
    return {
      path: $utils.getSharePath(),
    }
  },
  async onReset(loadmore = false) {
    const {
      data: { currentTab, navData, limit, searchText, currentTabList, list: lists },
    } = this
    this.setData({
      keyword: searchText,
      focus: false,
    })
    wx.showLoading({
      title: '加载中',
    })
    let list = [] as any
    try {
      switch (currentTab) {
        case 0:
          break
        case 1:
          break
        case 2:
          list = await userApi.searchUser({
            offset: loadmore ? navData[currentTab].offset : 0,
            limit,
            keyword: searchText,
          })
          break
        case 3:
          break
        case 4:
          list = await knowledgeApi.getKnowledge({
            offset: loadmore ? navData[currentTab].offset : 0,
            limit,
            keyword: searchText,
          })
          break
        case 5:
          break
        case 6:
          list = await activityApi.getActivityList({
            offset: loadmore ? navData[currentTab].offset : 0,
            limit,
            keyword: searchText,
          })
          break
        case 7:
          list = await knowAboutApi.getKnowAboutList({
            offset: loadmore ? navData[currentTab].offset : 0,
            limit,
            keyword: searchText,
            firstAnswer: 1,
          })
          break
        case 8:
          break
      }
      const isLastPage = list.length < limit
      !loadmore && currentTabList.push(currentTab)
      this.setData({
        [`list[${currentTab}]`]: loadmore ? [...lists[currentTab], ...list] : list,
        [`navData[${currentTab}].isLastPage`]: isLastPage,
        currentTabList,
        [`navData[${currentTab}].offset`]: loadmore
          ? list.length + lists[currentTab].length
          : list.length,
        [`navData[${currentTab}].show`]: list.length === 0 && !loadmore ? true : false,
      })
    } catch (error) {
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none',
        duration: 1000,
      })
      wx.hideLoading()
      wx.stopPullDownRefresh()
    }
    wx.hideLoading()
    wx.stopPullDownRefresh()
  },
  onPullDownRefresh() {
    this.onReset()
    wx.stopPullDownRefresh()
  },
  async onReachBottom() {
    if (this.data.navData[this.data.currentTab].isLastPage) {
      wx.showToast({
        title: '已没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.onReset(true)
  },
  onDownload() {
    $event.emit('download')
  },
  switchNav(event: WechatMiniprogram.CustomEvent) {
    const windowWidth = GlobalData.clientWidth
    const cur = event.currentTarget.dataset.current
    const {
      data: { currentTab, currentTabList },
    } = this
    //每个tab选项宽度占1/6
    const singleNavWidth = windowWidth / 6
    //tab选项居中
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth,
    })
    if (currentTab == cur) return
    this.setData({
      currentTab: cur,
    })
    if (currentTabList.indexOf(cur) === -1) {
      this.onReset()
    }
  },
  search() {
    const {
      data: { keyword, searchText },
    } = this
    if (keyword == searchText) return
    this.setData({
      navData: [
        { id: 2, name: '主播', offset: 0, isLastPage: false, loading: true },
        { id: 6, name: '球员', offset: 0, isLastPage: false, loading: true },
      ],
      list: [],
      show: true,
      currentTabList: [],
    })
    this.onReset()
  },
  onInputComment(event: WechatMiniprogram.CustomEvent) {
    this.setData({
      searchText: event.detail.value,
    })
  },
  /** 缓存改变状态 */
  changeTopic(topic: DomoTopic) {
    const topics = this.data.list[1] || []
    topics[topics.findIndex((i: any) => i.id === topic.id)] = topic
    this.setData({
      [`list[1]`]: topics,
    })
  },
  /** 删除圈子时改变缓存 */
  deleteTopic(topic: DomoTopic) {
    const topics = this.data.list[1] || []
    topics.splice(
      topics.findIndex((i: any) => i.id === topic.id),
      1,
    )
    this.setData({
      [`list[1]`]: topics,
    })
  },
  followAction(e: any) {
    const {
      data: { currentTab, followingOperations },
    } = this
    const {
      target: {
        dataset: { user, index },
      },
    } = e
    if (!followingOperations.includes(user.id)) {
      let method = 'followUser' as keyof typeof userApi
      // 已关注状态
      if (user.follower) {
        method = 'unFollowUser'
      }
      this.setData({
        followingOperations: [...followingOperations, user.id],
      })
      userApi[method](user.id as never).then(() => {
        const {
          data: { followingOperations: fo },
        } = this
        const i = fo.findIndex((f) => f === user.id)
        fo.splice(i, 1)
        this.setData({
          [`list[${currentTab}][${index}].follower`]: !user.follower,
          followingOperations: fo,
        })
      })
    }
  },
  goUser(event: any) {
    wx.navigateTo({
      url: `/mine/homePage/homePage?id=${event.currentTarget.dataset.id}`,
    })
  },
  themeDetail(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/theme/detail/detail?id=${id}`,
    })
  },
})
